package com.ruoyi.system.pay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.ruoyi.system.pay.config.AlipayConfig;
import com.ruoyi.system.pay.domain.po.PayOrder;
import com.ruoyi.system.pay.domain.po.PayRefund;
import com.ruoyi.system.pay.domain.dto.RefundRequestDTO;
import com.ruoyi.system.pay.domain.vo.PayRefundVO;
import com.ruoyi.system.pay.mapper.PayOrderMapper;
import com.ruoyi.system.pay.mapper.PayRefundMapper;
import com.ruoyi.system.pay.service.IRefundService;
import com.ruoyi.system.wnjk.contents.Contents;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 退款实现类
 */
@Slf4j
@Service
public class RefundServiceImpl implements IRefundService {

    @Autowired
    private PayOrderMapper payOrderMapper;

    @Autowired
    private PayRefundMapper payRefundMapper;

    @Autowired
    private AlipayConfig alipayConfig;

    /**
     * 申请退款
     */
//    @Override
    @Transactional
    public String requestRefund(String orderNumber, Double refundAmount) {
        // 1. 查询订单
        PayOrder order = payOrderMapper.findByOrderNumber(orderNumber);
        if (order == null || !"PAID".equals(order.getStatus())) {
            throw new RuntimeException("订单不存在或未支付，无法退款");
        }

        // 2. 检查是否已经退款
        List<PayRefund> refundList = payRefundMapper.findByOrderId(order.getId());
        BigDecimal totalRefunded = refundList.stream()
                .map(PayRefund::getRefundAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 3. 校验退款金额是否超限
        if (totalRefunded.add(BigDecimal.valueOf(refundAmount)).compareTo(order.getAmount()) > 0) {
            throw new RuntimeException("退款金额超出支付金额");
        }

        // 4. 生成退款记录
        PayRefund refund = new PayRefund();
        refund.setOrderId(order.getId());  // 订单ID
        refund.setTransactionId(Long.valueOf(order.getTransactionId()));  // 关联交易ID
        refund.setRefundAmount(BigDecimal.valueOf(refundAmount));  // 退款金额
        refund.setStatus("PROCESSING");  // 退款处理中
        refund.setReason("用户申请退款");  // 退款原因

        // 5. 插入退款记录
        payRefundMapper.insertRefund(refund);

        return "退款申请成功，等待处理";
    }

    /**
     * 查询退款状态
     */
    @Override
    public PayRefund getRefundStatus(Long refundId) {
        return payRefundMapper.findByOrderId(refundId).stream().findFirst().orElse(null);
    }

    /**
     * 统一退款接口实现
     */
    @Override
    public PayRefundVO unifiedRefund(RefundRequestDTO refundRequestDTO) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getGatewayUrl(),
                alipayConfig.getAppId(),
                alipayConfig.getMerchantPrivateKey(),
                "json",
                alipayConfig.getCharset(),
                alipayConfig.getAlipayPublicKey(),
                alipayConfig.getSignType()
        );

//        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
//        request.setBizContent("{\"out_trade_no\":\"" + refundRequestDTO.getSourceType() + refundRequestDTO.getOrderNumber() + "\","
//                + "\"refund_amount\":\"" + refundRequestDTO.getRefundAmount() + "\","
//                + "\"refund_reason\":\"" + refundRequestDTO.getRefundReason() + "\"}");
        // 构造请求参数以调用接口
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
// 设置商户订单号
        model.setOutTradeNo(refundRequestDTO.getSourceType() + refundRequestDTO.getOrderNumber());
        model.setRefundAmount(refundRequestDTO.getRefundAmount());
        if (refundRequestDTO.getOutRequestNo()!=null&& !refundRequestDTO.getOutRequestNo().equals("")) {
            model.setOutRequestNo(refundRequestDTO.getOutRequestNo());
        }
        model.setRefundReason(refundRequestDTO.getRefundReason());
        request.setBizModel(model);
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        PayRefundVO result = new PayRefundVO();
        System.out.println(response.getBody());
//        Map mapResponse = JSONObject.parseObject(response.getBody(), Map.class);
//        Map map = JSONObject.parseObject(mapResponse.get("alipay_trade_refund_response").toString(), Map.class);
//        System.out.println("mapResponse="+mapResponse);
//        System.out.println("mapResponse="+map);
        result.setCode(response.getCode());
        result.setMsg(response.getMsg());
        if (result.getCode().equals(Contents.Pay.REFUND_STATUS_SUCCESS)) {
            String outTradeNo = response.getOutTradeNo();
            result.setOrderNumber(outTradeNo.substring(2));
            result.setSourceType(outTradeNo.substring(0, 2));
            result.setRefundFee(response.getRefundFee());
            result.setTradeNo(response.getTradeNo());
        }
//        result.setCode(map.get("code").toString());
//        result.setMsg(map.get("msg").toString());
//        String outTradeNo = map.get("out_trade_no").toString();
        //解析订单号中的业务模块和订单号
//        result.setOrderNumber(outTradeNo.substring(2));
//        result.setSourceType(outTradeNo.substring(0,2));
//        result.setRefundFee(map.get("refund_fee").toString());
//        result.setTradeNo(map.get("trade_no").toString());
        return result;
    }
}
